package com.yy.service.BackgroundService.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.yy.domain.Admin;
import com.yy.mapper.BackgroundMapper.BAdminMapper;
import com.yy.service.BackgroundService.IBadminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BAdminServiceImpl implements IBadminService {

    @Autowired
    private BAdminMapper Mapper;
    @Override
    public List<Admin> selectAdminList(Admin admin) {
        return Mapper.selectAdminList(admin);
    }
    @Override
    public int updateAdminById(Admin admin) {
        return Mapper.updateAdminById(admin);
    }
    @Override
    public int deleteAdminById(int id) {
        return Mapper.deleteAdminById(id);
    }
    @Override
    public Admin selectAdminByUser(Admin admin) {
        // 从数据库中查询管理员信息
        Admin adminDB = Mapper.selectAdminByUser(admin);
        if (adminDB == null) {
            return null;
        }

        // 获取盐值和用户输入的密码
        String salt = adminDB.getSalt();
        String password = admin.getPassword();

        // 检查盐值和密码是否为空
        if (StrUtil.isBlank(salt) || StrUtil.isBlank(password)) {
            return null;
        }

        // 对盐值和密码进行 MD5 加密
        String encryptedPassword = SecureUtil.md5(salt + password);

        // 比较加密后的密码和数据库中存储的密码
        if (!encryptedPassword.equals(adminDB.getPassword())) {
            return null;
        }

        // 登录成功，使用 Sa-Token 进行登录操作
        StpUtil.login(adminDB.getId());
        return adminDB;
    }
    @Override
    public int InsertAdminByAdmin(Admin admin) {
        return Mapper.InsertAdminByAdmin(admin);
    }

    @Override
    public Boolean checkAdmin(Admin admin) {
        Admin admin1 = Mapper.selectAdminByUser(admin);
        if (admin1!=null){
            return true;
        }
        return false;
    }
}
